package com.jianganming.proxy.trends;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 */
public class ProxyPoint implements InvocationHandler {
    private TrainStation station;

    public TrainStation getProxy(Class<? extends TrainStation> clazz)throws Exception{
        this.station = clazz.newInstance();
        TrainStation o = (TrainStation)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
        return o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("sellTickets".equals(method.getName())) {
            //调用目标方法，获取返回的价格
            double price = (Double) method.invoke(station, args);
            //重新计算价格
            double price1 = price + (price * 0.05);
            System.out.println("代售收取5%手续费," + station.getName() + "原价：" + price);
            //返回计算后的新价格
            return price1;
        }else {
            return method.invoke(station, args);
        }
    }

    public static void main(String[] args)throws Exception {
        ProxyPoint proxyPoint = new ProxyPoint();
        //获取的是代理对象
        TrainStation guangzhou = proxyPoint.getProxy(GuangzhouTrainStation.class);
        //调用的是代理对象的方法也就是上面的invoke方法
        double price = guangzhou.sellTickets();
        System.out.println(guangzhou.getName()+"现价:"+price);

        double price2 = proxyPoint.getProxy(ShanghaiTrainStation.class).sellTickets();
        System.out.println(guangzhou.getName()+"现价："+price2);
    }


}

interface TrainStation{
    //售票
    double sellTickets();
    //地名
    String getName();
}

//目标类
class GuangzhouTrainStation implements TrainStation {
    private double price;

    @Override
    public double sellTickets() {
        price = 200d;
        System.out.println("广州火车站卖票");
        return price;
    }

    @Override
    public String getName() {
        return "广州";
    }
}

//目标类
class ShanghaiTrainStation implements TrainStation {
    private double price;

    @Override
    public double sellTickets() {
        price = 150d;
        System.out.println("上海火车站卖票");
        return price;
    }

    @Override
    public String getName() {
        return "上海";
    }
}